/**
 * 
 */
package com.tnl.web.interceptor;

import com.tnl.web.config.controller.Authentication;
import com.tnl.web.dao.AdminUserDAO;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.taglib.AccessorTags;
import com.tnl.web.util.qualifiers.AuditIt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.text.MessageFormat;

public class AuditInterceptor implements HandlerInterceptor {

	
	private static Logger logger = LoggerFactory
			.getLogger(AuditInterceptor.class);
	@Autowired
	private Authentication authentication;
	@Autowired
	private AdminUserDAO adminUserDAO;
	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("**preHandle**");
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		AuditIt auditIt = method.getAnnotation(AuditIt.class);
		if (null != auditIt) {
			String module = auditIt.module();
			String action = auditIt.action();
			String description = auditIt.description();
			//AdminUser userT = authentication.getCurrentUser();
			HttpSession session = request.getSession();
			String userId = (String) session.getAttribute("UserId");
			AdminUser user = null;
			String role = null;
			if (StringUtils.hasText(userId))
			{
				
				 user = adminUserDAO.findByID(Integer.valueOf(userId));
				 if (user!=null){
					int roleId = user.getRoleId();
					role = String.valueOf(roleId);
				 }
				 
			}
		
			//String userId = String.valueOf(user.getId());
			boolean hasPriv = AccessorTags.hasPermission(role, action);
			if (hasPriv)
			{
				logger.info(MessageFormat.format("[{0}]-[{1}] by {2}({3}).", module,
						action, null == user ? "anonymous" : user.getUsername(),
						description));
				//DB save
				return true;
			}
			String contextPath = request.getContextPath();
			logger.info(MessageFormat.format("{2} did not have the privilege [{0}]-[{1}] ", module,
					action, null == user ? "anonymous" : user.getUsername()));
			response.sendRedirect(contextPath+"/views/admin/errorpage.jsp");
			return false;
		}
		return true;
	}
	
	

	private boolean checkPermission() {
		// TODO Auto-generated method stub
		return false;
	}



	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
